package com.alstudio.net.protocol.xmpp.util;

import java.util.Random;

public class PackactIdGenerator {

	/* 随机数发送器。用于产生消息的本条id号 */
	private Random random;

	private long msgNum;
	public static PackactIdGenerator mInstance;

	// 随机id号得取值范围
	private char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
			+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();

	/**
	 * 获取XMPP id生成器实例
	 * 
	 * @return
	 */
	public static PackactIdGenerator getPackactIdGenerator() {
		if (mInstance == null) {
			mInstance = new PackactIdGenerator();
		}
		return mInstance;
	}

	public PackactIdGenerator() {
		random = new Random(System.currentTimeMillis());
	}

	/**
	 * 获取指定长度的随机字符串
	 * 
	 * @param length
	 * @return
	 */
	public String getPackactId(int length) {
		return randomString(length) + (msgNum++);
	}

	/**
	 * 获取随机的id号
	 * 
	 * @param length
	 * @return 随机的id号
	 * @author Alonso Lee
	 */
	private String randomString(int length) {
		if (length < 1) {
			return null;
		}
		// Create a char buffer to put random letters and numbers in.
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[random.nextInt(71)];
		}
		return new String(randBuffer);
	}
}
